package com.jblv.frame.common.fastdfs;

import com.google.gson.reflect.TypeToken;
import com.jblv.frame.common.exception.FrameException;
import com.jblv.frame.common.fastdfs.fdfs.FastResult;
import com.jblv.frame.common.fastdfs.fdfs.FileListDTO;
import com.jblv.frame.common.fastdfs.fdfs.LoadFile;
import com.jblv.frame.common.fastdfs.image.CustomPicSize;
import com.jblv.frame.common.fastdfs.image.PictureUtils;
import com.jblv.frame.common.utils.GsonUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.csource.common.MyException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
 * @author happyonion.yangtao
 * @version 1.0
 * @title FastDfsFileSystem
 * @projectName jblv-frame
 * @packageName com.jblv.common.fastdfs
 * @description 文件
 * @date Create at 2020/5/7 10:40
 * @since jdk1.8
 */

public class FastDfsFileSystem implements IFileSystem {
    private String appId;

    public FastDfsFileSystem() {
    }

    public FastDfsFileSystem(String resourceAppId) {
        this.appId = resourceAppId;
    }

    public String getFilePathById(String fileId) {
        return FastDfsUtils.getFilePathById(fileId);
    }

    public List<FastResult> uploadPic(List<File> files, List<String> fileNames) throws MyException {
        List<FastResult> fastResults = null;
        boolean flag = FastDfsUtils.validateFile(files, fileNames, 5242880L, ".jpg,.png,.bmp,.jpeg,.svg", true, "图片");
        if (flag) {
            fastResults = FastDfsUtils.uploadFile(files, fileNames);
        }

        return fastResults;
    }

    public List<FastResult> uploadPicWithInfo(List<File> files, List<String> fileNames, List<Integer> heights, List<Integer> widths) throws MyException {
        List<FastResult> fastResults = null;
        boolean flag = FastDfsUtils.validateFile(files, fileNames, 5242880L, ".jpg,.png,.bmp,.jpeg,.svg", true, "图片");
        if (flag) {
            fastResults = FastDfsUtils.uploadPic(files, fileNames, heights, widths);
        }

        return fastResults;
    }

    public List<FastResult> uploadFile(List<File> files, List<String> fileNames) throws MyException {
        List<FastResult> fastResults = null;
        boolean flag = FastDfsUtils.validateFile(files, fileNames, 2147483648L, ".xls,.xlsx,.pptx,.pdf,.docx,.doc,.ppt,.apk,.txt,.keystore,.mobileprovision,.p12,.zip,.pem,.csv,.jks,.rar,.face-ios,.face-android,.aar,.framework,.bundle,.jar,.a,.mp4,.mp3,.m4a", true, "文件");
        if (flag) {
            fastResults = FastDfsUtils.uploadFile(files, fileNames);
        }

        return fastResults;
    }

    public FastResult uploadFile(byte[] bytes, String fileExtName, Map<String, String> nameValuePairMap) {
        return FastDfsUtils.uploadFile(bytes, fileExtName, nameValuePairMap);
    }

    public FastResult uploadFile(byte[] bytes, String fileExtName, Map<String, String> nameValuePairMap, boolean ifZoom) {
        return FastDfsUtils.uploadFile(bytes, fileExtName, nameValuePairMap, ifZoom);
    }

    public FastResult upload(InputStream is, String fileId, String fileName, String contentType) {
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);
        Map<String, String> nameValuePairMap = new HashMap();
        nameValuePairMap.put("_FILE_NAME", fileName);
        return FastDfsUtils.uploadFile(is, prefix, nameValuePairMap);
    }

    public FastResult uploadCut(String fileId, int x, int y, int width, int height) throws Exception {
        CustomPicSize customPicSize = new CustomPicSize(x, y, width, height);
        return PictureUtils.cutCustomAndUploadFile(fileId, customPicSize);
    }

    public LoadFile downFile(String fileId) {
        return FastDfsUtils.downFile(fileId);
    }

    public String getFileName(LoadFile loadFile) {
        Map<String, String> nameValuePairMap = loadFile.getNameValuePairMap();
        if (nameValuePairMap != null && nameValuePairMap.size() > 0) {
            String fileName = (String)nameValuePairMap.get("_FILE_NAME");
            if (StringUtils.isNotEmpty(fileName)) {
                return fileName;
            }

            String fileExtName = (String)nameValuePairMap.get("FILE_EXT_NAME");
            if (StringUtils.isNotEmpty(fileExtName)) {
                return System.currentTimeMillis() + "." + fileExtName;
            }
        }

        return String.valueOf(System.currentTimeMillis());
    }

    public List<FileListDTO> getFileDTOList(String fileJsonArrayStr) {
        if (!StringUtils.isEmpty(fileJsonArrayStr) && !"[]".equals(fileJsonArrayStr)) {
            List<FileListDTO> fileDTOList = (List) GsonUtils.jsonToBean(fileJsonArrayStr, (new TypeToken<List<FileListDTO>>() {
            }).getType());
            Iterator var3 = fileDTOList.iterator();

            while(var3.hasNext()) {
                FileListDTO fileDTO = (FileListDTO)var3.next();
                fileDTO.setFilePath(this.getFilePathById(fileDTO.getFileId()));
            }

            return fileDTOList;
        } else {
            return null;
        }
    }

    public List<FileListDTO> getFileInfoList(String fileJsonArrayStr) throws FrameException {
        if (!StringUtils.isEmpty(fileJsonArrayStr) && !"[]".equals(fileJsonArrayStr)) {
            FileListDTO dto = null;
            List<FileListDTO> fileInfoList = new ArrayList();
            List<FileListDTO> idList = (List)GsonUtils.jsonToBean(fileJsonArrayStr, (new TypeToken<List<FileListDTO>>() {
            }).getType());
            Iterator var5 = idList.iterator();

            while(var5.hasNext()) {
                FileListDTO idDTO = (FileListDTO)var5.next();
                dto = this.getFileInfo(idDTO.getFileId());
                if (dto != null) {
                    dto.setFileId(idDTO.getFileId());
                    dto.setFilePath(this.getFilePathById(idDTO.getFileId()));
                    fileInfoList.add(dto);
                } else {
                    fileInfoList.add(idDTO);
                }
            }

            return fileInfoList;
        } else {
            return null;
        }
    }

    public FileListDTO getFileInfo(String fileId) throws FrameException {
        if (StringUtils.isEmpty(fileId)) {
            return null;
        } else {
            LoadFile loadFile = this.downFile(fileId);
            FileListDTO targetInfo = new FileListDTO();
            Map<String, String> nameValuePairMap = loadFile.getNameValuePairMap();
            if (nameValuePairMap != null && nameValuePairMap.size() > 0) {
                String height = (String)nameValuePairMap.get("_HEIGHT");
                if (StringUtils.isNotEmpty(height)) {
                    targetInfo.setHeight(Integer.parseInt(height));
                }

                String width = (String)nameValuePairMap.get("_WIDTH");
                if (StringUtils.isNotEmpty(width)) {
                    targetInfo.setWidth(Integer.parseInt(width));
                }

                String fileName = (String)nameValuePairMap.get("_FILE_NAME");
                if (StringUtils.isNotEmpty(fileName)) {
                    targetInfo.setFileName(fileName);
                }

                String fileExt = (String)nameValuePairMap.get("FILE_EXT_NAME");
                if (StringUtils.isNotEmpty(fileExt)) {
                    targetInfo.setFormat(fileExt);
                }

                int size = loadFile.getBytes().length;
                targetInfo.setSize(String.valueOf(size));
            }

            return targetInfo;
        }
    }

    public void zoom(File file, String fileId, int width, int height) throws FrameException {
        if (StringUtils.isEmpty(fileId)) {
            throw new FrameException("文件标识为空");
        } else {
            int i = fileId.lastIndexOf(46);
            if (i < 0) {
                throw new FrameException("请选择jpg后缀或png后缀的图片文件");
            } else {
                String suffix = fileId.substring(i);
                if (!suffix.equals(".jpg") && !suffix.equals(".png")) {
                    throw new FrameException("请选择jpg后缀或png后缀的图片文件");
                } else {
                    String zoomFileId = fileId + "_" + width + "x" + height + suffix;
                    String zommFilePath = this.getFilePathById(zoomFileId);
                    URL url = null;
                    HttpURLConnection httpUrl = null;
                    InputStream inputStream = null;

                    try {
                        url = new URL(zommFilePath);
                        httpUrl = (HttpURLConnection)url.openConnection();
                        httpUrl.connect();
                        inputStream = httpUrl.getInputStream();
                        FileUtils.copyInputStreamToFile(inputStream, file);
                    } catch (IOException var13) {
                        var13.printStackTrace();
                    }
                }
            }
        }
    }

    public boolean patchUpload(MultipartFile multipartFile) {
        return false;
    }

    private class ImageInfoObject {
        private String value;

        private ImageInfoObject() {
        }

        public String getValue() {
            return this.value;
        }

        public void setValue(String value) {
            this.value = value;
        }
    }
}
